package com.loginer.controller;

import java.io.IOException;
import java.util.Arrays;
import java.util.Map;


import com.loginer.config.JwtUtil;
import com.loginer.config.OSSFileUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import com.loginer.entity.UserEntity;
import com.loginer.service.UserService;
import com.bwie.common.utils.PageUtils;
import com.bwie.common.utils.R;
import org.springframework.web.multipart.MultipartFile;


/**
 * 
 *
 * @author wangmo
 * @email wangmo@gmail.com
 * @date 2021-10-14 17:03:13
 */
@RestController
@RequestMapping("/loginer/user")
//@CrossOrigin
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private JwtUtil jwtUtil;

    /**
     * 列表
     */
    @RequestMapping("/list")

    public R list(@RequestParam Map<String, Object> params){
        PageUtils page = userService.queryPage(params);

        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{yhId}")
    public R info(@PathVariable("yhId") Integer yhId){
		UserEntity user = userService.getById(yhId);

        return R.ok().put("user", user);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    public R save(@RequestBody UserEntity user){
		userService.save(user);

        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    public R update(@RequestBody UserEntity user){
		userService.updateById(user);

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    public R delete(@RequestBody Integer[] yhIds){
		userService.removeByIds(Arrays.asList(yhIds));

        return R.ok();
    }


    @PostMapping("/userLogin")
    public R userLogin(@RequestBody UserEntity userEntity){
        UserEntity user = userService.userLogin(userEntity);
        if (user != null){
            if (user.getYhPwd().equals(userEntity.getYhPwd())){
                String token = jwtUtil.createJWT(user.getYhName(), user.getYhPwd(), "token");
                return R.ok().put("user",user).put("token",token);
            }
        }
        return  R.error();
    }

    @PostMapping("/upload")
    public String upload(MultipartFile file) throws IOException {
        String s = OSSFileUtil.uploadFile(file);
        return s;
    }

}
